/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tsystems.school.server;

/**
 *
 * @author 123
 */
import com.google.gson.Gson;
import com.tsystems.school.nutils.Message;
import com.tsystems.school.nutils.MessageType;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class Worker implements Runnable {

    protected Socket clientSocket;
    private String clientInfo;
    public Worker(Socket clientSocket) {
        this.clientSocket = clientSocket;
        clientInfo = "client: " + clientSocket.getInetAddress() + ": " + clientSocket.getPort();
        System.out.println("new " + clientInfo + "\n");
    }

    @Override
    public void run() {
        try {
            InputStream input = clientSocket.getInputStream();
            OutputStream output = clientSocket.getOutputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            PrintWriter pw = new PrintWriter(output);
            long time = System.currentTimeMillis();
//            output.write("Hi!\n".getBytes());

            String str;
            System.out.println(clientInfo + " said: \n");
            while ((str = reader.readLine()) != null && !str.equals("bye")) {
//                System.out.println(new Gson().fromJson(str, Message.class));
                System.out.println(Message.LoadFromJSON(str).getType());
                Message msg = new Message();
                msg.setType(MessageType.OK);
                output.write(msg.toJSON().getBytes());
            }
//            output.write("Good bye!".getBytes());
            System.out.println("THE END");
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
